﻿#region

using System;

#endregion

namespace wsy.ext.Devlib.ExtensionMethods
{
    public static class FlagExt
    {
        /// <summary>
        ///     取整数的某一位
        /// </summary>
        /// <param name="resource">要取某一位的整数</param>
        /// <param name="mask">要取的位置索引，自右至左为0-7</param>
        /// <returns>返回某一位的值（0或者1）</returns>
        public static int GetIntegerSomeBit(this int resource, int mask)
        {
            return (resource >> mask) & 1;
        }

        /// <summary>
        ///     将整数的某位置为0或1
        /// </summary>
        /// <param name="resource">整数</param>
        /// <param name="mask">整数的某位，自右至左为0-7</param>
        /// <param name="flag">是否置1，TURE表示置1，FALSE表示置0</param>
        /// <returns>返回修改过的值</returns>
        public static int SetIntegerSomeBit(this int resource, int mask, bool flag)
        {
            if (flag)
                resource |= 0x1 << mask;
            else
                resource &= ~(0x1 << mask);
            return resource;
        }

        public static TEnum SetFlags<TEnum>(this TEnum resource, TEnum mask, bool flag) where TEnum : struct
        {
            int Resource = Convert.ToInt32(resource);
            int Mask = Convert.ToInt32(mask);
            int num = Convert.ToString(Convert.ToInt32(mask), 2).Length;
            for (int i = 0; i < num; i++)
                if (GetIntegerSomeBit(Mask, i) == 1)
                    Resource = SetIntegerSomeBit(Resource, i, flag);
            return (TEnum) Enum.ToObject(typeof(TEnum), Resource);
        }
    }
}